package com.zhuoyue.web.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.zhuoyue.common.constant.HttpStatus;
import com.zhuoyue.common.core.domain.AjaxResult;
import com.zhuoyue.common.core.domain.YunPianMessage;
import com.zhuoyue.common.core.domain.YunPianUser;
import com.zhuoyue.common.core.domain.entity.SysDictData;
import com.zhuoyue.common.core.domain.entity.SysThirdData;
import com.zhuoyue.common.core.page.TableDataInfo;
import com.zhuoyue.common.utils.DateUtils;
import com.zhuoyue.common.utils.StringUtils;
import com.zhuoyue.system.mapper.SysDictDataMapper;
import com.zhuoyue.system.mapper.SysThirdDataMapper;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zhanghui
 * @date 2021/9/14 10:58
 */
@RestController
@RequestMapping("/third/yunpian")
public class YunPianController {
    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Autowired
    private SysThirdDataMapper sysThirdDataMapper;

    @Value("${yunpian.getUser}")
    private String getUserUrl;

    @Value("${yunpian.listMsg}")
    private String listMsgUrl;

    /**
     * 根据组织ID查询云片短信账户的信息
     *
     * @param deptId
     * @return
     */
    @GetMapping("/user/get")
    public AjaxResult selectYunPianUser(Long deptId) {
        // 先查询字典数组中第三方平台dictCode
        SysDictData dictData = sysDictDataMapper.getYunPianDictData();
        SysThirdData yunPianData = sysThirdDataMapper.getYunPianDataByDeptId(dictData.getDictCode(), deptId);
        if (yunPianData == null) {
            return AjaxResult.error("该组织没有添加云片短信");
        }

        // 使用apikey进行请求
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("apikey", yunPianData.getDataKey());

        // 设置请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        httpHeaders.set("Accept", "application/json;charset=utf-8");

        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        String jsonStr = restTemplate.exchange(getUserUrl, HttpMethod.POST, httpEntity, String.class).getBody();
        YunPianUser yunPianUser = JSONObject.parseObject(jsonStr, YunPianUser.class);
        return AjaxResult.success(yunPianUser);
    }

    /**
     * 查询短信列表
     *
     * @param deptId    组织ID
     * @param mobile    手机号(完整手机号, 不能模糊搜索)
     * @param startTime 开始时间戳
     * @param endTime   结束时间戳
     * @param page_num  页码(1开始)
     * @param page_size 页大小
     * @param type      短信类型(默认为空(国内), global(国际), all(国内与国际))
     * @return
     */
    @GetMapping("/message/list")
    public TableDataInfo getMessageList(Long deptId, String mobile, Long startTime, Long endTime, Integer page_num, Integer page_size, String type) {
        TableDataInfo tableDataInfo = new TableDataInfo();
        if (mobile != null && (mobile.length() > 0 && mobile.length() != 11)) {
            tableDataInfo.setMsg("查询成功");
            tableDataInfo.setCode(200);
            tableDataInfo.setTotal(0);
            tableDataInfo.setRows(new ArrayList<>());
            return tableDataInfo;
        }

        // 先查询字典数组中第三方平台dictCode, 获取apikey
        SysDictData dictData = sysDictDataMapper.getYunPianDictData();
        SysThirdData yunPianData = sysThirdDataMapper.getYunPianDataByDeptId(dictData.getDictCode(), deptId);
        if (yunPianData == null) {
            tableDataInfo.setCode(HttpStatus.ERROR);
            tableDataInfo.setTotal(0);
            tableDataInfo.setRows(new ArrayList<>());
            return null;
        }

        // 将时间戳转换为字符串
        String start_time = DateFormatUtils.format(DateUtils.getStartTimeOfDay(new Date(startTime)), "yyyy-MM-dd HH:mm:ss");
        String ent_time = DateFormatUtils.format(DateUtils.getEndTimeOfDay(new Date(endTime)), "yyyy-MM-dd HH:mm:ss");

        // 查询参数
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("apikey", yunPianData.getDataKey());
        if (StringUtils.isNotEmpty(mobile)) {
            params.add("mobile", mobile);
        }
        params.add("start_time", start_time);
        params.add("end_time", ent_time);
        params.add("page_num", page_num.toString());
        params.add("page_size", page_size.toString());
        if ("all".equals(type) || "global".equals(type)) {
            params.add("type", type);
        }

        // 设置请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        httpHeaders.set("Accept", "application/json;charset=utf-8");

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(params, httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        String jsonStr = restTemplate.exchange(listMsgUrl, HttpMethod.POST, httpEntity, String.class).getBody();

        List<YunPianMessage> messageList = JSONObject.parseObject(jsonStr, List.class);
        tableDataInfo.setMsg("查询成功");
        tableDataInfo.setCode(200);
        tableDataInfo.setTotal(messageList.size());
        tableDataInfo.setRows(messageList);
        return tableDataInfo;
    }

    @GetMapping("/fee/get")
    public AjaxResult getFee(HttpServletRequest request) {
        System.out.println("请求IP：" + request.getRemoteAddr());


        if (request.getHeader("x-forwarded-for") != null) {
            System.out.println(request.getHeader("x-forwarded-for"));
        }
        return AjaxResult.success();
    }
}
